import {showToast} from '@/common/ToastUtil.js';
import CacheUtil from '@/common/CacheUtil.js';

function getWxStar(str){
	let star = "******"
	if(str && str.length > 4){
		var regex = /^(.{0,2}).*?(.{2})$/; // 匹配字符串的前两位和最后2位
		star = str.replace(regex, "$1****$2")
	}
	return star
}

function getDistanceAndOnline(list){
	let distanceList = CacheUtil.getDistance();
	list.forEach(item => {
		let flag = true;
		if (!hasCacheDistance(distanceList, item)) {
			item.distance = (Math.random() * (20 - 0.2) + 0.2).toFixed(1);
			item.online = Math.floor(Math.random() * 30) + 1;
			let data = {
				userId: item.id,
				distance: item.distance,
				nick: item.nick,
				online: item.online,
				time: new Date().getTime()
			}
			distanceList.push(data);
		}
	});
	CacheUtil.setDistance(distanceList);
	return list;
}

function hasCacheDistance(userDistanceList, item) {
	let flag = false
	userDistanceList.forEach(data => {
		if (item.id == data.userId) {
			item.distance = data.distance;
			item.online = data.online;
			let now = new Date().getTime();
			let old = data.time;
			if ((now - old) > 1000 * 60 * 20) {
				item.distance = (Math.random() * (20 - 0.2) + 0.2).toFixed(1);
				item.online = Math.floor(Math.random() * 30) + 1;
				data.time = now;
				data.distance = item.distance;
				data.online = item.online;
			}
			flag = true;
		}
	});
	return flag;
}


export default {
	//ToastUtil.js
	showToast,
	getWxStar,
	getDistanceAndOnline
}